import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { allAsyncRoutes, anyRoute, staticRoutes } from "@/router/routes";
import { getUserInfoApi, loginApi, logoutApi } from "@/api/acl/login";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
import { cloneDeep } from "lodash";

/* 
对所有的异步路由进行过滤得到用户的权限路由表
*/
function filterAsyncRoutes(
  allAsyncRoutes: RouteRecordRaw[],
  routeNames: string[]
): RouteRecordRaw[] {
  return allAsyncRoutes.filter((route) => {
    if (!routeNames.includes(route.name as string)) return false;
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRoutes(route.children, routeNames);
    }

    return true;
  });
}
// 注册指定的路由表
function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => router.addRoute(route));
}

// 重置路由  只注册静态的初始路由
function resetRoute() {
  // 得到所有已经注册的路由, 根据路由的name进行删除
  router
    .getRoutes()
    .forEach((route) => route.name && router.removeRoute(route.name));
  // 重新注册静态路由
  addRoutes(staticRoutes);
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],

    buttons: [],
    roles: [],
  }),

  actions: {
    async login(username: string, password: string) {
      /* return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (username==='admin' && password==='111111') {
            const token = 'token-atguigu'
            setToken(token)
            this.token = token
            resolve(token)
          } else {
            reject(new Error('用户名或密码错误!'))
            ElMessage.error('用户名或密码错误!')
          }
        }, 1000)
      }) */
      const result = await loginApi(username, password);
      const token = result.token;
      this.token = token;
      setToken(token);
    },

    async getInfo() {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = "admin";
      //     this.avatar =
      //       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
      //     this.menuRoutes = staticRoutes;
      //     resolve({ name: this.name, avatar: this.avatar, token: this.token });
      //   }, 1000);
      // });
      const result = await getUserInfoApi();
      const { name, avatar, routes, buttons, roles } = result;
      this.name = name;
      this.avatar = avatar;
      //将静态路由表保存到state
      // this.menuRoutes = staticRoutes;

      // 保存按钮权限列表和角色列表
      this.buttons = buttons;
      this.roles = roles;

      // 根据路由权限数据routes从allAsyncRoutes过滤出用户权限路由表, 进行动态注册

      const asyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes), routes);
      // asyncRoutes.forEach((route) => router.addRoute(route));

      // router.addRoute(anyRoute); // 最后注册通配路由

      addRoutes([...asyncRoutes, anyRoute]);

      // 根据静态路由表+用户权限路由表合并生成权限导航菜单
      this.menuRoutes = [...staticRoutes, ...asyncRoutes];
    },

    async reset() {
      //如果当前有用户名,请求退出登陆接口
      if (this.name) {
        await logoutApi(); // 加await后, 下面的代码是在请求成功后执行的
      }
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      this.buttons = [];
      this.menuRoutes = [];
      // 重置注册的路由 => 只注册静态路由, 清除动态注册的路由
      resetRoute();
    },
  },
});
